<?php

namespace app\api\controller;

use app\common\model\ChatRoom;
use app\common\model\Config as ConfigModel;
use app\common\controller\Api;
use app\common\model\User;
use fast\Random;
use think\Cache;
use think\Db;
use think\Validate;

class Login extends Api
{
    protected $noNeedLogin = ['login','register','mobileLogin','miniLogin','modifyPwd','third'];
    protected $noNeedRight = '*';

    /**
     * 账号密码登录
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     * @path api/login/login
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $duan = $this->request->post('duan');
        if(!$duan){
            $this->error("缺少参数duan");
        }
        if (!$account) {
            $this->error("账号不能为空");
        }
        if(!$password){
            $this->error("密码不能为空");
        }
        $ret = $this->auth->login($account, $password,$duan);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo($duan)];
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 注册账号
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $code 验证码
     * @param string $password 密码
     * @param string $c_password  确认密码
     * @path api/login/register
     */
    public function register()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $password = $this->request->post('password');
        $c_password = $this->request->post('c_password');
        $duan = $this->request->post("duan",2);
        if (!$mobile) {
            $this->error(__('手机号不能为空'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号有误'));
        }
        $info = User::where(["tel"=>$mobile,"logout"=>'0'])->find();
        if($info){
            $this->error(__('手机号已存在'));
        }
        $name = 'register_'.$mobile;
        $yzm = Cache::get($name);
        if(empty($yzm) || $yzm == false){
            $this->error("请先发送验证码");
        }
        if(!$code){
            $this->error("验证码不能为空");
        }
        if($yzm!=$code){
            $this->error(0,'验证码有误');
        }
        if (!$password) {
            $this->error(__('密码不能为空'));
        }
        if (!$c_password) {
            $this->error(__('确认密码不能为空'));
        }
        if($password != $c_password){
            $this->error(__('两次密码不一致'));
        }
        $ret = $this->auth->register($mobile, $password,$duan,[]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo($duan)];
            $this->success(__('注册成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @path api/login/mobileLogin
     */
    public function mobileLogin()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $duan = $this->request->post('duan');
        if(!$duan){
            $this->error("缺少参数duan");
        }
        if (!$mobile) {
            $this->error(__('手机号不能为空'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式错误'));
        }
        if(!$code){
            $this->error(__('验证码不能为空'));
        }
        $name = 'login_'.$mobile;
        $yzm = Cache::get($name);
        if(empty($yzm) || $yzm == false){
            $this->error("请先发送验证码");
        }
        if(!$code){
            $this->error("验证码不能为空");
        }
        if($yzm!=$code){
            $this->error(0,'验证码有误');
        }
        $info = User::where(["tel"=>$mobile,"logout"=>'0'])->order("user_id","desc")->find();
        if(!$info){
            $this->error(__('账号不存在,请先注册'));
        }
        //如果已经有账号则直接登录
        $ret = $this->auth->direct($info->user_id,$duan);
//        $user = \app\common\model\User::getByMobile($mobile);
//        if ($user) {
//            if ($user->status != 'normal') {
//                $this->error(__('Account is locked'));
//            }
//            //如果已经有账号则直接登录
//            $ret = $this->auth->direct($user->id);
//        } else {
//            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
//        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo($duan)];
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 微信快捷登录
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $code = $this->request->param('code');
        $duan = $this->request->param('duan');
        if(!isset($duan) || empty($duan)){
            $this->error("缺少参数duan");
        }
        $wx_appid = ConfigModel::getConfigValue("k_wx_appid");
        $wx_appsecret = ConfigModel::getConfigValue("k_wx_appsecret");
        if (empty($code)){
            $this->error("code不能为空");
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $wx_appid . "&secret=" . $wx_appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $str = file_get_contents($url);
        $arr = json_decode((string) $str,true);
        if (!isset($arr['openid']) || !empty($arr['openid'])){
            $union_id = $arr['unionid'];
            $app_open_id =  $arr['openid'];
            $info = User::appLogin($union_id,$app_open_id);
            if ($info->is_jin == 1){
                $this->error('您的账号已被禁用,请联系管理员');
            }
            User::where("user_id",$info->user_id)->update(["app_open_id"=>$app_open_id]);
            if ($info) {
                $this->auth->smallLogin($info->user_id,$duan);
                $data = ['userinfo' => $this->auth->getUserinfo($duan)];
                $this->success(__('登录成功'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            $this->error('登录失败,'.$arr['errmsg']);
        }
    }

    /**
     * 小程序授权登录
     * @path api/login/miniLogin
     * @param string $code
     * */
    public function miniLogin()
    {
        $code = $this->request->param('code');
        $wx_appid = ConfigModel::getConfigValue("wx_appid");
        $wx_appsecret = ConfigModel::getConfigValue("wx_appsecret");
        if (empty($code)){
            $this->error("code不能为空");
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$wx_appid}&secret={$wx_appsecret}&js_code=$code&grant_type=authorization_code";
        $str = file_get_contents($url);
        $arr = json_decode((string) $str,true);
        if (!isset($arr['openid']) || !empty($arr['openid'])){
            if(!isset($arr['unionid']) || empty($arr['unionid'])){
                $this->error('小程序未在微信开放平台绑定');
            }
            $union_id = $arr['unionid'];
            $openid =  $arr['openid'];
            $info = User::login($union_id,$openid);
            if ($info->is_jin == 1){
                $this->error('您的账号已被禁用,请联系管理员');
            }
            if ($info) {
                $this->auth->smallLogin($info->user_id,1);
                $data = ['userinfo' => $this->auth->getUserinfo(1)];
                $this->success(__('登录成功'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            $this->error('登录失败,'.$arr['errmsg']);
        }
    }

    /**
     * 绑定手机号
     * @path api/login/bindPhone
     * @param string $code
     * */
    public function bindPhone()
    {
        $code = $this->request->param('code');
        if (empty($code)){
            $this->error("code不能为空");
        }
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if($user->tel){
            $this->success("绑定成功");
        }
        $lifeTime = 2 * 3000;
        //Cache::rm('access_token_user');   //清空缓存使用
        $access_token = Cache::get('access_token_user');
        if(empty($access_token)){
            $appid = ConfigModel::getConfigValue("wx_appid");
            $secret = ConfigModel::getConfigValue("wx_appsecret");
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $access_token_data = file_get_contents($url);
            $access_token_data = json_decode($access_token_data,true);
            $access_token = $access_token_data['access_token'];
            Cache::set('access_token_user',$access_token,$lifeTime);
        }
        $get_phone_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";
        $requestBody = json_encode(array('code'=>$code));
        $context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded"."Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]);
        $response = file_get_contents($get_phone_url, false, $context);
        $arr = json_decode($response,true);
        if ($arr['errcode']==0){
            $phone = $arr['phone_info']['phoneNumber'];
            $user = User::find($user_id);
            $phoneInfo = User::where(["tel"=>$phone,"is_jin"=>'0',"logout"=>'0'])->find();
            $user->tel = $phone;
            $res = $user->save();
            if ($res){
                if(!empty($phoneInfo) && $phoneInfo->user_id < $user_id){
                    $user_data = [];
                    $user_data['open_id'] = $user->open_id;
                    $user_data['unionid'] = $user->unionid;
                    User::where("user_id",$phoneInfo->user_id)->update($user_data);
                    User::where("user_id",$user_id)->delete();
                    //if(!$phoneInfo['identification']){
                    //    $identification = Random::alnum(16).'_'.$phoneInfo['user_id'];
                    //    $user_token = ChatRoom::getUserToken($identification);
                    //    $h_user_data = [];
                    //    $h_user_data['identification'] = $identification;
                    //    $h_user_data['access_token'] = $user_token['data']['access_token'];
                    //    $h_user_data['uuid'] = $user_token['data']['user']['uuid'];
                    //    Db::name("user")->where("user_id",$phoneInfo['user_id'])->update($h_user_data);
                    //}
                    $this->auth->smallLogin($phoneInfo->user_id,1);
                }else{
                    //if(!$user->identification){
                    //    $identification = Random::alnum(16).'_'.$user_id;
                    //    $user_token = ChatRoom::getUserToken($identification);
                    //    $h_user_data = [];
                    //    $h_user_data['identification'] = $identification;
                    //    $h_user_data['access_token'] = $user_token['data']['access_token'];
                    //    $h_user_data['uuid'] = $user_token['data']['user']['uuid'];
                    //    Db::name("user")->where("user_id",$user_id)->update($h_user_data);
                    //}
                    $this->auth->smallLogin($user_id,1);
                }
                $data = ['userinfo' => $this->auth->getUserinfo(1)];
                $this->success(__('绑定成功'), $data);
            }else{
                $this->error('绑定失败');
            }
        }else{
            $this->error($arr['errmsg']);
        }
    }

    /**
     * 修改密码
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     * @path api/login/modifyPwd
     */
    public function modifyPwd()
    {
        $mobile = $this->request->post("mobile");
        $code = $this->request->post("code");
        $password = $this->request->post('password');
        $c_password = $this->request->post('c_password');
        if (!$mobile) {
            $this->error('手机号不能为空');
        }
        $info = User::where(["tel"=>$mobile,"logout"=>'0'])->find();
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号有误');
        }
        if(!$info){
            $this->error('账号不存在,请先注册');
        }
        $name = 'modify_'.$mobile;
        $yzm = Cache::get($name);
        if(empty($yzm) || $yzm == false){
            $this->error("请先发送验证码");
        }
        if(!$code){
            $this->error("验证码不能为空");
        }
        if($yzm!=$code){
            $this->error('验证码有误');
        }
        if (!$password) {
            $this->error('密码不能为空');
        }
        if (!$c_password) {
            $this->error('确认密码不能为空');
        }
        if($password != $c_password){
            $this->error('两次密码不一致');
        }
        $ret = $this->auth->changePwd($info['user_id'],$password);
        if ($ret) {
            $this->success('修改成功');
        } else {
            $this->error($this->auth->getError());
        }

        //模拟一次登录
//        $this->auth->direct($user->id);as
//        $ret = $this->auth->changepwd($newpassword, '', true);
//        if ($ret) {
//            $this->success(__('Reset password successful'));
//        } else {
//            $this->error($this->auth->getError());
//        }
    }

    /**
     * APP绑定手机号
     * @path api/login/appBindPhone
     * @param string $code
     * */
    public function appBindPhone()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if($user->tel){
            $this->error("手机号已绑定");
        }
        $mobile = $this->request->post("mobile");
        $code = $this->request->post("code");
        $password = $this->request->post('password');
        $c_password = $this->request->post('c_password');
        if (!$mobile) {
            $this->error('手机号不能为空');
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号有误');
        }
        $name = 'bind_'.$mobile;
        $yzm = Cache::get($name);
        if(empty($yzm) || $yzm == false){
            $this->error("请先发送验证码");
        }
        if(!$code){
            $this->error("验证码不能为空");
        }
        if($yzm!=$code){
            $this->error('验证码有误');
        }
        if (!$password) {
            $this->error('密码不能为空');
        }
        if (!$c_password) {
            $this->error('确认密码不能为空');
        }
        if($password != $c_password){
            $this->error('两次密码不一致');
        }
        $phoneInfo = User::where(["tel"=>$mobile,"is_jin"=>'0',"logout"=>'0'])->find();
        if(!empty($phoneInfo) && $phoneInfo->user_id < $user_id){
            $user_data = [];
            $user_data['app_open_id'] = $user->app_open_id;
            $user_data['unionid'] = $user->unionid;
            User::where("user_id",$phoneInfo->user_id)->update($user_data);
            User::where("user_id",$user_id)->delete();
            if(!$phoneInfo['identification']){
                $identification = Random::alnum(16).'_'.$phoneInfo['user_id'];
                $user_token = ChatRoom::getUserToken($identification);
                $h_user_data = [];
                $h_user_data['identification'] = $identification;
                $h_user_data['access_token'] = $user_token['data']['access_token'];
                $h_user_data['uuid'] = $user_token['data']['user']['uuid'];
                $h_user_data['password'] = $this->auth->getPwd($password);
                Db::name("user")->where("user_id",$phoneInfo['user_id'])->update($h_user_data);
            }
            $this->success("绑定成功");
        }else{
            if(!$user->identification){
                $identification = Random::alnum(16).'_'.$user_id;
                $user_token = ChatRoom::getUserToken($identification);
                $h_user_data = [];
                $h_user_data['identification'] = $identification;
                $h_user_data['access_token'] = $user_token['data']['access_token'];
                $h_user_data['uuid'] = $user_token['data']['user']['uuid'];
                Db::name("user")->where("user_id",$user_id)->update($h_user_data);
            }
            $pwd = $this->auth->getPwd($password);
            Db::name("user")->where("user_id",$user_id)->update(["tel"=>$mobile,"password"=>$pwd]);
            $this->success("绑定成功");
        }

    }

}
